package com.zhu.day.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

public class NumberFormatUtils {

    public static StringBuffer formatNum(int num) {
        StringBuffer sb = new StringBuffer();
        BigDecimal b1 = new BigDecimal("10000");
        BigDecimal b2 = new BigDecimal("100000000");
        BigDecimal b3 = new BigDecimal(num);

        String formatNumStr = "";
        String unit = "";
        // 以万为单位处理
        if (b3.compareTo(b1) == -1) {
            formatNumStr = b3.toString();
        } else if ((b3.compareTo(b1) == 0 && b3.compareTo(b1) == 1)
                || b3.compareTo(b2) == -1) {
            unit = "万";
            formatNumStr = b3.divide(b1,2, BigDecimal.ROUND_HALF_UP).toString();
        } else if (b3.compareTo(b2) == 0 || b3.compareTo(b2) == 1) {
            unit = "亿";
            formatNumStr = b3.divide(b2,2, BigDecimal.ROUND_HALF_UP).toString();

        }
        if (!"".equals(formatNumStr)) {
            int i = formatNumStr.indexOf(".");
            if (i == -1) {
                sb.append(formatNumStr).append(unit);
            } else {
                i = i + 1;
                String v = formatNumStr.substring(i, i + 2);
                if (!v.equals("0")) {
                    sb.append(formatNumStr.substring(0, i + 1)).append(unit);
                } else {
                    sb.append(formatNumStr.substring(0, i - 1)).append(unit);
                }
            }
        }
        if (sb.length() == 0)
            return sb.append("0");
        return sb;
    }

    public static void main(String[] args) {
//        BigDecimal bigDecimal = new BigDecimal("13140000");
//        String text = getText(bigDecimal);
//        System.out.println(text);

        Map<Long, String> loveStarPrizeMap = new HashMap<>();
        loveStarPrizeMap.put(1314l,"缘分值达到1314万，mvp用户获得奖励");
        loveStarPrizeMap.put(5200l,"缘分值达到1314万，mvp用户获得奖励");
        loveStarPrizeMap.put(9900l,"缘分值达到1314万，mvp用户获得奖励");

        Optional<String> configScore = getConfigScore(loveStarPrizeMap, 1315l);
        System.out.println(configScore.get());
    }

    public static String getText(BigDecimal score){
        BigDecimal init = new BigDecimal("10000");
        BigDecimal divide = score.divide(init, 2, RoundingMode.DOWN);
        String text = String.format("获得幸运机会\n缘分值%s万\n夺得超级流量卡",divide);
        return text;
    }


    public static <T> Optional<T> getConfigScore(Map<Long, T> configs, Long score) {

        Set<Long> keys = configs.keySet();
        Optional<Long> key = keys.stream().sorted(Comparator.reverseOrder()).filter(val -> score.compareTo(val) >= 0).findFirst();
        return key.flatMap(val -> Optional.ofNullable(configs.get(val)));
    }
}

